<template>
  <div class="pd-le-ri">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <el-icon :size="11">
            <user-filled />
          </el-icon> 趣味小知识
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div style="min-width: 800px; display: flex">
        <div style="margin: 0 10px">
          <el-button type="success" @click="addAdvert">增加趣味小知识</el-button>
        </div>
      </div>
      <div style="margin: 20px 0 30px">
        <el-table :data="tableData.arr" border style="width: 100%" :stripe="true">
          <el-table-column prop="id" label="ID" width="100"></el-table-column>
          <el-table-column align="center" label="图片" width="200">
          <template v-slot="scope">
            <el-image style="width: 50px; height: 50px" fit="cover" :src="scope.row.img"
              :preview-src-list="[scope.row.img]"></el-image>
          </template>
          </el-table-column>
          <el-table-column prop="title" label="标题" width="100"></el-table-column>
          <el-table-column prop="profile" label="简介" width="200"></el-table-column>
          <el-table-column prop="category" label="专栏" width="150"></el-table-column>
          <el-table-column prop="story" label="内容"></el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template v-slot="scope">
              <el-button size="small" type="danger" @click="closeAdmin(scope.row.id)">删除</el-button>
              <el-button size="small" type="success" @click="changeSubject(scope.row)">修改</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="margin-bottom: 10px">
       <div class="demo-pagination-block">
          <el-pagination
            :page-size="10"
            layout="total, prev, pager, next, jumper"
            :total="total"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>
      </div>
    </div>
    <el-dialog v-model="dialogVisible" title="新增趣味小知识" width="30%">
      <el-form :model="form" label-width="80px">
        <el-form-item label="标题">
          <el-input placeholder="请输入标题" v-model="form.title" type="input" />
        </el-form-item>
        <el-form-item label="简介">
          <el-input :rows="3" placeholder="请输入解析简介" v-model="form.profile" type="textarea" />
        </el-form-item>
        <el-form-item label="专栏">
          <el-select v-model="form.categoryId" placeholder="请选择专栏">
            <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="内容">
          <el-input  :rows="5"  placeholder="请输入解析内容" v-model="form.story" type="textarea" />
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            class="upload-demo"
            :show-file-list="false"
            :action="BASE_URL_18089 + `/file/upload`"
            :on-success="successLoad"
            :on-error="errorLoad"
            :before-close="handleClose"
          >
            <el-icon class="el-icon--upload" v-if="!url"><upload-filled /></el-icon>
            <div class="el-upload__text" v-if="!url">
              <em style="color: #000">点击上传</em>
            </div>
            <img v-if="url" :src="url" class="upload-img" />
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addKnowledgeHandle">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible1" title="修改趣味小知识" width="30%">
      <el-form :model="fromUpdate" label-width="80px">
        <el-form-item label="标题">
          <el-input placeholder="请输入标题" v-model="fromUpdate.title" type="input" />
        </el-form-item>
        <el-form-item label="简介">
          <el-input :rows="3" placeholder="请输入解析简介" v-model="fromUpdate.profile" type="textarea" />
        </el-form-item>
        <el-form-item label="专栏">
          <el-select v-model="fromUpdate.categoryId" placeholder="请选择专栏">
            <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="内容">
          <el-input  :rows="5"  placeholder="请输入解析内容" v-model="fromUpdate.story" type="textarea" />
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            class="upload-demo"
            :show-file-list="false"
            :action="BASE_URL_18089 + `/file/upload`"
            :on-success="successLoad"
            :on-error="errorLoad"
            :before-close="handleClose"
          >
            <el-icon class="el-icon--upload" v-if="!url"><upload-filled /></el-icon>
            <div class="el-upload__text" v-if="!url">
              <em style="color: #000">点击上传</em>
            </div>
            <img v-if="url" :src="url" class="upload-img" />
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible1 = false">取消</el-button>
          <el-button type="primary" @click="updateKnowledge">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, onMounted } from "vue";
import { toRaw } from '@vue/reactivity'
import {
  getKnowledge,
  addKnowledge,
  deleteKnowledge,
  editKnowledge,
  getCategory
} from "../../http/school/school";
import { BASE_URL_18089 } from "@/http/request"

import { UserFilled, UploadFilled } from "@element-plus/icons";
import { ElMessageBox } from "element-plus";
import { ElMessage } from 'element-plus'

export default defineComponent({
  components: {
    UserFilled,
    UploadFilled
  },
  setup() {
    let tableData = reactive({
      arr: [],
    });
    let url = ref("");
    let total = ref(1);
    let page = ref(1);
    let userId = ref("");
    let danger = reactive({
      reason: "",
      userId: "",
    });
    const regionId = ref('');
    let typeList: any = ref([]);
    let categoryList: any = ref([])
    const dialogVisible = ref(false);
    const dialogVisible1 = ref(false);
    let form:any = reactive({
      title: '',
      profile: '',
      categoryId: '',
      category: '',
      img: url.value,
      story: ''
  })
    const fromUpdate:any = reactive({
        title: '',
        profile: '',
        categoryId: '',
        category: '',
        img: url.value,
        story: ''
    })
    let apiCategory:any = []

    onMounted(() => {
      getList();
    });

    const getList = async () => {
      const data = {
        page: page.value,
        size: 10
      }
      const [subjectList, categoryListReq] = await Promise.all([getKnowledge(data), getCategory({page: 1, size: 1000})]);
      const subjectData:any =  subjectList.data
      tableData.arr = subjectData.records;
      total.value = subjectData.total

       const categoryData:any = categoryListReq && categoryListReq.data
        categoryList.value = categoryData.records
        apiCategory = categoryData.records
    };

    const handleCurrentChange = (e: number) => {
      page.value = e;
      getList();
    };

    const clickBtn = () => {
      getList();
    };

    const closeAdmin = async (e: any) => {
      ElMessageBox.confirm(
        "你确认删除该知识吗?",
        "提示",
        {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(async () => {
        const params = {
          id: e
        }
        await deleteKnowledge(params)
        getList()
      });
    };

    const addAdvert = async () => {
      dialogVisible.value = true;
    }

    const handleChange = async (e:any) => {
      await form.imgImgLists.push(toRaw(e.response).msg);
    }

    const changeSubject = (row:any) => {
      const {title, profile, categoryId, category, img, story, id} = row
      // console.log(categoryId, category)
      console.log(row)
      dialogVisible1.value = true;
      fromUpdate.title = title,
      fromUpdate.profile = profile,
      fromUpdate.categoryId = category,
      fromUpdate.category = category,
      fromUpdate.img = img,
      fromUpdate.story = story,
      fromUpdate.id = id
    }

    const addKnowledgeHandle = async () => {
      const data = form
      data.img = url.value
      if(data.categoryId) {
        data.category = apiCategory.find((v:any) => v.id === data.categoryId).name
      }
      await addKnowledge(data)
      clearFormData()
      dialogVisible.value = false;
      getList();
    }
    
    const clearFormData = () => {
      form.title = '',
      form.profile = '',
      form.categoryId = '',
      form.category = '',
      form.img = '',
      form.story = ''
    }

    const updateKnowledge = async () => {
      const data = fromUpdate
      data.img = url.value
      await editKnowledge(fromUpdate)
      dialogVisible1.value = false;
      getList();
    }

  const successLoad = (res:any) => {
        if(res.code == 200) {
            ElMessage.success('上传成功！')
            url.value = res.data
        }else {
            ElMessage.error(res.msg)
        }
    }

     const handleClose = () => {
        dialogVisible.value = false
        url.value = ""
    }

    
    //文件上传失败
    const errorLoad = () => {
        ElMessage.error('上传失败！')
    }
    return {
      tableData,
      total,
      userId,
      dialogVisible,
      dialogVisible1,
      danger,
      typeList,
      categoryList,
      regionId,
      form,
      fromUpdate,
      changeSubject,
      clickBtn,
      handleChange,
      //   openAdmin,
      handleCurrentChange,
      closeAdmin,
      addAdvert,
      addKnowledgeHandle,
      updateKnowledge,
      // upload img
      successLoad,
      handleClose,
      errorLoad,
      url,
      BASE_URL_18089
    };
  },
});
</script>

<style scoped>

</style>
